<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Configuration
 *
 * @author MinhNguyen
 */
class User {

    //put your code here
    public $id;
    public $name;
    public $password;
    public $email;
    public $phone;
    public $address;
    public $company;
    public $position;
    public $dateRegistered;
    public $token;
    public $type;
    public $active;
    public $avatar;
    public static $instance;

    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function __get($name) {
        return $this->$name;
    }

    public function __set($name, $value) {
        $this->$name = $value;
    }

    /**
     * It's constuctor of User with email
     */
    public function __construct() {
        //allocate your stuff
    }

    /**
     * Print message if email is not found in database
     * or print error message if can not connect database
     */
    public static function withEmail($email) {
        $instance = new self();
        $db = Database::getInstance();
        $query = "SELECT * FROM users WHERE email = '$email'";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $rows = $result->dataTable->rows[0];
                $instance->id = $rows["userid"];
                $instance->name = $rows["fullname"];
                $instance->password = $rows["password"];
                $instance->email = $rows["email"];
                $instance->phone = $rows["phone"];
                $instance->address = $rows["address"];
                $instance->company = $rows["company"];
                $instance->position = $rows["position"];
                $instance->dateRegistered = new DateTime($rows["dateregistered"]);
                $instance->token = $rows["token"];
                $instance->type = $rows["type"];
                $instance->avatar = $rows["avatar"];
                $instance->active = $rows["active"];
                return $instance;
            } else {
                return NULL;
            }
        } else {
            return NULL;
        }
    }

    public static function withData($fullname, $password, $email) {
        $instance = new self();
        $instance->fullname = $fullname;
        $instance->password = $password;
        $instance->email = $email;
        return $instance;
    }

    public static function withId($id) {
        $instance = new self();
        $db = Database::getInstance();
        $query = "SELECT * FROM users WHERE userid = '$id'";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $rows = $result->dataTable->rows[0];
                $instance->id = $rows["userid"];
                $instance->name = $rows["fullname"];
                $instance->password = $rows["password"];
                $instance->email = $rows["email"];
                $instance->phone = $rows["phone"];
                $instance->address = $rows["address"];
                $instance->company = $rows["company"];
                $instance->position = $rows["position"];
                $instance->dateRegistered = new DateTime($rows["dateregistered"]);
                $instance->token = $rows["token"];
                $instance->type = $rows["type"];
                $instance->avatar = $rows["avatar"];
                $instance->active = $rows["active"];
                return $instance;
            } else {
                    $controller = new ErrorController(new Error(), new ErrorView(), "404", "Not found any user with provided id $id");
                    $controller->returnError();
                return NULL;
            }
        } else {
            $controller = new ErrorController(new Error(), new ErrorView, $result->returnCode, $result->message);
            $controller->returnError();
            return NULL;
        }
    }
   
    /**
     * 
     * @param type $_filter
     * @return type
     * get email and password from client by $_filter
     * then check data from db to set Session and return user's email 
     * or return false for log in
     */
    public static function login($login) {
        $db = Database::getInstance();
        $email = $login["email"];
        $password = $login["password"];
        $query = "SELECT * FROM users WHERE email = '$email' AND active='1'";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $row = $result->dataTable->rows[0];
                if ($row["password"] === $password) {
                    session_start();
                    global $userId;
                    $_SESSION['bret_userid'] = $row["userid"];
                    $userId = $row["userid"];
                    session_write_close();
                    return array(
                        'id' => $row["userid"],
                        'email' => $row["email"],
                        'password' => md5("thebret"),
                        'name' => $row["fullname"],
                        'company' => $row["company"],
                        'address' => $row["address"],
                        'phone' => $row["phone"],
                        'position' => $row["position"],
                        'dateregistered' => $row["dateregistered"],
                        'token' => $row["token"],
                        'type' => $row["type"]
                    );
                } else {
                    return NULL;
                }
            } else {
                 /*$controller = new ErrorController(new Error(), new ErrorView(), 
                  "404", "Not found any user with provided email");
                  $controller->returnError();*/
                return NULL;
            }
        } else {
              /*$controller = new ErrorController(new Error(), new ErrorView, 
              $result->returnCode, $result->message);
              $controller->returnError();*/
            return NULL;
        }
    }

    /**
     * 
     * @param type $_filter
     * @return type
     * get register user of information from client by $_filter
     * then insert into database and return result user's email or false
     */
    public static function addUser($user) {
        $tUser = self::withEmail($user["email"]);
        if (!is_object($tUser)) {
            $db = Database::getInstance();
            $id = $db->getID("users", "userid");
            $name = $user["name"];
            $password = $user["password"];
            $email = $user["email"];
            $phone = $user["phone"];
            $address = $user["address"];
            $company = $user["company"];
            $token = "0";
            $type = 3;
            $active = 0;
            $query = "INSERT INTO users (userid, email, password, fullname, company, address, 
                phone, dateregistered, token, type, active) VALUES 
                ('$id', '$email', '$password', '$name', '$company', '$address', "
                    . "'$phone', NOW(), '$token', '$type', '$active')";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                return $id;
            } else {
                return 'false';
            }
        } else {
            return 'duplicated';
        }
    }

    public static function deleteUser($userid) {
        if (User::getCurrentUserId()) {
            $db = Database::getInstance();
            $query = "DELETE FROM users WHERE userid = '$userid'";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                return "true";
            } else {
                /* $controller = new ErrorController(new Error(), new ErrorView, 
                  $result->returnCode, $result->message);
                  $controller->returnError(); */
                return "false";
            }
        } else {
            return "false";
        }
    }

    public static function getLogedInUser() {
        global $userId;
        return self::withId($userId);
    }

    public static function changePassword($oldPassword, $newPassword) {
        global $userId;
        $user = User::withId($userId);
        if ($user->password == $oldPassword) {
            $user->password = $newPassword;
            $userController = new UserController($user, new UserView());
            if ($userController->Save()){
                return "succeed";
            } else {
                return "failed";
            }
        }
        else {
            return 'Wrong password';
        }
    }
    
    public static function updateProfile($name, $phone, $company, $position) {
        global $userId;
        $user = User::withId($userId);
        $user->name = $name;
        $user->phone = $phone;
        $user->company = $company;
        $user->position = $position;
        $userController = new UserController($user, new UserView());
        if ($userController->Save())
            return "succeed";
        else
            return "failed";
    }

    public static function getCurrentUserId() {
        global $userId;
        return $userId;
    }
    
    public static function getFolder() {
        if (self::getCurrentUserId()) {
            $db = Database::getInstance();
            $userId = self::getCurrentUserId();
            $user = User::withId($userId);
            $query = "SELECT * FROM folders WHERE userid = '$user->id'";
            //$query = "SELECT * FROM folders LEFT JOIN foldershare ON folders.folderid = foldershare.folderid WHERE foldershare.sharewith = '$user->teamId' ORDER BY folders.folderid";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow > 0) {
                    foreach ($result->dataTable->rows as $row) {
                        $id = $row['id'];
                        $name = $row['name'];
                        $parentid = $row["parentid"];
                        $folderId = "$folderId$id;";
                        $foldername = "$foldername$name;";
                        $parentId = "$parentId$parentid;";
                    }
                    return array(
                        'folderid' => $folderId,
                        'foldername' => $foldername,
                        'parentid' => $parentId
                    );
                } else {
                    /* $controller = new ErrorController(new Error(), new ErrorView(), 
                      "404", "Not found any user with provided email");
                      $controller->returnError(); */
                    return array(
                        'folderid' => 'undefined',
                        'foldername' => 'undefined',
                        'parentid' => 'undefined'
                    );
                }
            } else {
                /* $controller = new ErrorController(new Error(), new ErrorView, 
                  $result->returnCode, $result->message);
                  $controller->returnError(); */
                return array(
                    'folderid' => 'undefined',
                    'foldername' => 'undefined',
                    'parentid' => 'undefined'
                );
            }
        } else {
            return array(
                'folderid' => 'undefined',
                'foldername' => 'undefined',
                'parentid' => 'undefined'
            );
        }
    }
    
    public static function getBret() {
        if (self::getCurrentUserId()) {
            $db = Database::getInstance();
            $userId = self::getCurrentUserId();
            $user = User::withId($userId);
            $query = "SELECT * FROM brets WHERE userid = '$user->id'";
            //$query = "SELECT * FROM folders LEFT JOIN foldershare ON folders.folderid = foldershare.folderid WHERE foldershare.sharewith = '$user->teamId' ORDER BY folders.folderid";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow > 0) {
                    foreach ($result->dataTable->rows as $row) {
                        $id = $row['id'];
                        $name = $row['name'];
                        $folderid = $row["folderid"];
                        $bretId = "$bretId$id;";
                        $bretName = "$bretName$name;";
                        $folderId = "$folderId$folderid;";
                    }
                    return array(
                        'bretid' => $bretId,
                        'bretname' => $bretName,
                        'folderid' => $folderId
                    );
                } else {
                    /* $controller = new ErrorController(new Error(), new ErrorView(), 
                      "404", "Not found any user with provided email");
                      $controller->returnError(); */
                    return array(
                        'bretid' => 'undefined',
                        'bretname' => 'undefined',
                        'folderid' => 'undefined'
                    );
                }
            } else {
                /* $controller = new ErrorController(new Error(), new ErrorView, 
                  $result->returnCode, $result->message);
                  $controller->returnError(); */
                return array(
                    'bretid' => 'undefined',
                    'bretname' => 'undefined',
                    'folderid' => 'undefined'
                );
            }
        } else {
            return array(
                'bretid' => 'undefined',
                'bretname' => 'undefined',
                'folderid' => 'undefined'
            );
        }
    }
    
    public static function uploadAvatar($file) {
        global $host;
        $target_dir = "Images/User/";
        $target_dir = $target_dir . basename($file["name"]);
        $uploadOk = 1;
        $uploadFile_type = $file["type"];

        // Check file size
        if ($uploadFile_size > 500000) {
            $uploadOk = 0;
        }

        // Only GIF, JPG, PNG files allowed 
        if ($uploadFile_type != "image/gif" && $uploadFile_type != "image/png" && $uploadFile_type != "image/jpeg") {
            $uploadOk = 0;
        }

        // Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 1) {
            if (move_uploaded_file($file["tmp_name"], $target_dir)) {
                //insert info to database
                $db = Database::getInstance();
                global $userId;
                $query = "UPDATE users SET avatar='$target_dir' WHERE userid='$userId'";
                $result = $db->query($query);
                if ($result->returnCode == 200) {
                    echo 'succeed';
                } else {
                    echo 'fail';
                }
            } else {
                echo "fail";
            }
        } else {
            echo 'fail';
        }
    }
    
    public static function deleteMulti($ids) {
        $db = Database::getInstance();
        $query = "DELETE FROM users WHERE userid IN (";
        for ($i = 0; $i < sizeof($ids); $i++) {
            if($i == sizeof($ids) - 1) {
                $query .= $ids[$i].")";
            } else {
                $query .= $ids[$i].', ';
            }
        }
        $result = $db->query($query);
        if($result->returnCode == 200) {
            return 'succeed';
        } else {
            return 'failed';
        }
    }
    
    public static function enableMulti($ids) {
        $db = Database::getInstance();
        $query = "UPDATE users SET active='1' WHERE userid IN (";
        for ($i = 0; $i < sizeof($ids); $i++) {
            if($i == sizeof($ids) - 1) {
                $query .= $ids[$i].")";
            } else {
                $query .= $ids[$i].', ';
            }
        }
        $result = $db->query($query);
        if($result->returnCode == 200) {
            return 'succeed';
        } else {
            return 'failed';
        }
    }
    
    public static function disableMulti($ids) {
        $db = Database::getInstance();
        $query = "UPDATE users SET active='0' WHERE userid IN (";
        for ($i = 0; $i < sizeof($ids); $i++) {
            if($i == sizeof($ids) - 1) {
                $query .= $ids[$i].")";
            } else {
                $query .= $ids[$i].', ';
            }
        }
        $result = $db->query($query);
        if($result->returnCode == 200) {
            return 'succeed';
        } else {
            return 'failed';
        }
    }
}
